package git.soulbgm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import git.soulbgm.common.base.BaseController;
import git.soulbgm.common.pojo.QueryDto;
import git.soulbgm.common.pojo.Response;
import git.soulbgm.pojo.SysConfigInfo;
import git.soulbgm.pojo.dto.SysConfigInfoDto;
import git.soulbgm.service.SysConfigInfoService;
import git.soulbgm.utils.EasyPoiUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import static git.soulbgm.common.MonitorConstants.*;

/**
 * 系统参数信息控制器
 *
 * @author SoulBGM
 * @date 2022/07/13 17:40
 */
@RestController
@RequestMapping("system/config")
public class SysConfigInfoController extends BaseController {

    private final SysConfigInfoService sysConfigInfoService;

    public SysConfigInfoController(SysConfigInfoService sysConfigInfoService) {
        this.sysConfigInfoService = sysConfigInfoService;
    }

    @PostMapping("list")
    public Response list(@RequestBody QueryDto<SysConfigInfo> dto, Page<SysConfigInfo> queryPage) {
        Page<SysConfigInfo> resultPage = sysConfigInfoService.page(queryPage, new QueryWrapper<>(dto.getData()));
        return success(resultPage);
    }

    @GetMapping("get/{name}")
    public String get(@PathVariable("name") String name) {
        return sysConfigInfoService.getSysConfig(name);
    }

    @GetMapping("getSysConfig")
    public Response getSysConfig(String name) {
        return success((Object) sysConfigInfoService.getSysConfig(name));
    }

    @GetMapping("export")
    public void export(SysConfigInfo info, HttpServletResponse response) {
        List<SysConfigInfo> list = sysConfigInfoService.list(new QueryWrapper<>(info));
        try {
            EasyPoiUtil.exportExcel(response, "系统参数信息数据", list, SysConfigInfo.class);
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }

    @PostMapping("add")
    public Response add(@RequestBody SysConfigInfoDto info) {
        boolean result = sysConfigInfoService.save(info);
        return result ? success() : error();
    }

    @PostMapping("remove")
    public Response remove(String ids) {
        boolean result = sysConfigInfoService.removeByIds(Arrays.asList(ids.split(",")));
        return result ? success() : error();
    }

    @PostMapping("edit")
    public Response edit(SysConfigInfo info) {
        boolean result = sysConfigInfoService.updateById(info);
        return result ? success() : error();
    }

    @PostMapping("checkSysConfigInfoUnique")
    public String checkNodeCodeUnique(SysConfigInfo info) {
        return sysConfigInfoService.checkUnique(info) ? UNIQUE : NOT_UNIQUE;
    }

}
